package com.offline.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.offdissys.common.core.constant.TokenResultEnum;
import com.offdissys.common.core.exception.CommException;
import com.offdissys.common.utils.domain.BaseTokenObj;
import com.offdissys.common.utils.domain.TokenConstants;
import com.offdissys.common.utils.token.AbstractToken;
import com.offdissys.common.utils.token.DefaultToken;
import com.offline.gateway.config.IgnoreWhiteProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ZhangHaiWen
 * @title: AuthFilter
 * @projectName parent
 * @description: 用户权限filter
 * @date 2022/2/1510:31
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;

    /**
     * 用户登录验证模块
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        /*if(CollectionUtil.contains(ignoreWhiteProperties.getWhites(),path)){
            // 白名单包含则直接放行
            return chain.filter(exchange);
        }*/
        if(true){
            // 白名单包含则直接放行
            return chain.filter(exchange);
        }
        String tokenStr = getToken(exchange.getRequest());
        // 校验token是否失效
        AbstractToken token = new DefaultToken();
        boolean checkResult = token.checkToken(tokenStr, BaseTokenObj.class);
        if(checkResult){
            return chain.filter(exchange);
        }
        throw new CommException(TokenResultEnum.TOKEN_INVALID_ERROR);
    }

    @Override
    public int getOrder() {
        return 1;
    }

    /**
     * 获取请求头中的token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.HTTP_HEADER);
        if (StrUtil.isBlank(token))
        {
            throw new CommException(TokenResultEnum.TOKEN_NOT_EXIST);
        }
        return token;
    }
}
